<!--进货统计-->
<template>
  <div class="total-purchase">
    <!-- 时间筛选 -->
    <el-tabs v-model="activeTime" @update:modelValue="handleTabChange">
      <el-tab-pane label="今日" name="today"></el-tab-pane>
      <el-tab-pane label="昨日" name="yesterday"></el-tab-pane>
      <el-tab-pane label="本周" name="week"></el-tab-pane>
      <el-tab-pane label="上周" name="lastWeek"></el-tab-pane>
      <el-tab-pane label="本月" name="month"></el-tab-pane>
      <el-tab-pane label="上月" name="lastMonth"></el-tab-pane>
    </el-tabs>

    <!-- 查询条件 -->
    <el-form label-width="100px" :inline="true" class="demo-form-inline" :model="searchform" ref="searchref">
      <!-- 第一行：进货单号和供应商 -->
      <div class="form-row">
        <el-form-item label="进货单号" prop="code">
          <el-input placeholder="请输入进货单号" v-model="searchform.code"></el-input>
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-select v-model="searchform.supplier" placeholder="请选择供应商" style="width:200px;">
            <el-option v-for="item in suppliers" :key="item.sup_id" :label="item.sup_name" :value="item.sup_id"></el-option>
          </el-select>
        </el-form-item>
      </div>

      <!-- 第二行：进货负责人、进货部门、进货日期 -->
      <div class="form-row">
        <el-form-item label="进货负责人" prop="person">
          <el-select v-model="searchform.person" placeholder="请选择进货负责人" style="width:200px;">
            <el-option v-for="item in users" :key="item.user_id" :label="item.user_name" :value="item.user_id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="进货部门" prop="department">
          <el-select v-model="searchform.department" placeholder="请选择进货部门" style="width:200px;">
            <el-option v-for="item in deps" :key="item.department_id" :label="item.department_name" :value="item.department_id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="进货日期" prop="date">
          <el-date-picker v-model="searchform.date" format="YYYY-MM-DD" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" style="width: 350px;" />
        </el-form-item>
      </div>

      <!-- 第三行：重置和查询按钮 -->
      <div class="form-row">
        <el-form-item>
          <el-button @click="Reset">重置</el-button>
          <el-button type="success" @click="Search">查询</el-button>
        </el-form-item>
      </div>
    </el-form>

    <!-- 统计数据 -->
    <div class="stats-box">
      <div class="stat-item">
        <h3>{{ totalAmount }}</h3>
        <p>进货订单总金额</p>
      </div>
      <div class="stat-item">
        <h3>{{ totalSupplier }}</h3>
        <p>供应商数量</p>
      </div>
      <div class="stat-item">
        <h3>{{ totalOrder }}</h3>
        <p>进货订单数量</p>
      </div>
    </div>

    <!-- 导出和刷新按钮 -->
    <div class="action-buttons">
      <el-button @click="Export">导出</el-button>
      <el-button @click="Refresh">刷新</el-button>
    </div>

    <el-table 
      :data="tableData" 
      :border="true" 
      style="width: 100%; margin-top: 20px;"
      :row-key="rowKey"
      :tree-props="{children: 'details'}"
      default-expand-all
      @selection-change="handleSelectionChange"
    >
      <!-- 主表列保持不变 -->
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="pur_code" label="进货单号" width="220"></el-table-column>
      <el-table-column prop="pur_date" label="进货日期" width="200"></el-table-column>
      <el-table-column prop="sup_name" label="供应商名称" width="200"></el-table-column>
      <el-table-column prop="pur_depName" label="进货部门" width="200"></el-table-column>
      <el-table-column prop="pur_userName" label="进货负责人" width="200"></el-table-column>
      
      <el-table-column label="货品明细">
          <el-table-column prop="proc_name" label="货品名称" width="200"></el-table-column>
          <el-table-column prop="proc_code" label="货品编号" width="200"></el-table-column>
          <el-table-column prop="proc_pur_num" label="进货数量" width="200"></el-table-column>
          <el-table-column prop="proc_pur_total" label="进货金额" width="200">
              <template #default="scope">
                <span v-if="scope.row.proc_pur_total !== undefined">
                  {{ Number(scope.row.proc_pur_total).toFixed(2) }}
                </span>
                <span v-else></span>
              </template>
          </el-table-column>
      </el-table-column>
    </el-table>
    <!-- 分页控件 -->
     <!-- 页码 -->
     <el-pagination :page-size="pageSize" :pager-count="11" layout="prev, pager, next,jumper" :total="total"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>
  </div>
</template>

<script>
import {ref,reactive,onMounted, computed} from 'vue';
import http from '../auth/index';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';//路由
import * as XLSX from 'xlsx';
export default {
setup(){
  //表格数据
      const tableData=ref([]);
      const currentPage = ref(1);
      const pageSize = ref(5);
      const total = ref(0);
      //时间筛选
      const activeTime=ref('today');
      //时间筛选
      const timeRange=ref([]);
      //查询条件
      const searchref=ref(null);
      const searchform=reactive({
        code:'',
        supplier:'',
        person:'',
        department:'',
        date:[null,null]
      });
      //进货总金额
      const totalAmount=ref(0);
      //供应商数量
      const totalSupplier=ref(0);
      //进货订单数量
      const totalOrder=ref(0);

      //重置
      function Reset(){
        searchref.value.resetFields();
        All();
      }

      //查询
      function Search(){
        All();
      }

      //日期转换格式
      function formatDateTime(dateStr) {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const d = String(date.getDate()).padStart(2, '0');
        const h = String(date.getHours()).padStart(2, '0');
        const min = String(date.getMinutes()).padStart(2, '0');
        const s = String(date.getSeconds()).padStart(2, '0');
        return `${y}-${m}-${d} ${h}:${min}:${s}`;
      }

      //查询所有供应商
      const suppliers=ref([]);
        function GetSuppliers(){
            return http.get("/Supplier/GetAllSupplier")
            .then(res=>{
                suppliers.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询所有部门
        const deps=ref([]);
        function GetDepartments(){
            return http.get("/Department/GetDepartments")
            .then(res=>{
                deps.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询所有用户
        const users=ref([]);
        function GetUsers(){
            return http.get("/User/GetAllUser")
            .then(res=>{
                users.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询数据
        function All(){
          http.get("/Purchase_h/Purchase_hTJ",{
            params:{
              timeType:activeTime.value,
              code:searchform.code,
              sup:searchform.supplier,
              user:searchform.person,
              dep:searchform.department,
              starttime:searchform.date[0],
              endtime:searchform.date[1],
              page: currentPage.value,
              pagesize: pageSize.value
            }
          }).then(res=>{
            // 格式化为树形结构
            tableData.value = formatTableData(res.data.list);
            total.value = res.data.total;
            totalAmount.value = res.data.totalAmount;
            totalSupplier.value = res.data.totalSupplier;
            totalOrder.value = res.data.totalOrder;
          }).catch(err=>{
            console.log(err);
          })
        }

        //刷新
        function Refresh(){
          http.get("/Purchase_h/Refresh",{
            params:{
              timeType:activeTime.value,
              code:searchform.code,
              sup:searchform.supplier,
              user:searchform.person,
              dep:searchform.department,
              starttime:searchform.date[0],
              endtime:searchform.date[1],
              page: currentPage.value,
              pagesize: pageSize.value
            }
          }).then(res=>{
            ElMessage.success("刷新成功");
            All();
          }).catch(err=>{
            console.log(err);
          })
        }

        //转换数据格式
        function formatTableData(rawList) {
          const map = {};
          rawList.forEach(item => {
            const key = item.pur_id;
            if (!map[key]) {
              map[key] = {
                pur_code: item.pur_code,
                pur_date: formatDateTime(item.pur_date),
                sup_name: item.sup_name,
                pur_depName: item.pur_depName,
                pur_userName: item.pur_userName,
                details: []
              };
            }
            map[key].details.push({
              purd_id: item.purd_id,
              proc_name: item.proc_name,
              proc_code: item.proc_code,
              proc_pur_num: item.proc_pur_num,
              proc_pur_total: item.proc_pur_total
            });
          });
          return Object.values(map);
        }

        //行键
        function rowKey(row) {
          // 明细有 purd_id，主单有 pur_code
          return row.purd_id ? 'd_' + row.purd_id : 'h_' + row.pur_code;
        }

        //分页
        function handlePageChange(page) {
          currentPage.value = page;
          All();
        }

        //时间筛选
        function handleTabChange(name) {
          activeTime.value =name;
          console.log(activeTime.value);
          All();
        }

        //选中的数据
        const selectedRows = ref([]);
        function handleSelectionChange(selection) {
          selectedRows.value = selection;
        }

        //导出
        function Export() {
           // 如果没选，提示
          if (!selectedRows.value.length) {
            ElMessage.warning('请先选择要导出的单据！');
            return;
          }
          // 1. 组装表头和数据
          const header = [
            '进货单号', '进货日期', '供应商名称', '进货部门', '进货负责人',
            '货品名称', '货品编号', '进货数量', '进货金额'
          ];
          const data = [];

          tableData.value.forEach(main => {
            if (main.details && main.details.length > 0) {
              main.details.forEach(detail => {
                data.push([
                  main.pur_code,
                  main.pur_date,
                  main.sup_name,
                  main.pur_depName,
                  main.pur_userName,
                  detail.proc_name,
                  detail.proc_code,
                  detail.proc_pur_num,
                  detail.proc_pur_total
                ]);
              });
            } else {
              // 没有明细时也导出主单信息
              data.push([
                main.pur_code,
                main.pur_date,
                main.sup_name,
                main.pur_depName,
                main.pur_userName,
                '', '', '', ''
              ]);
            }
          });

          // 2. 生成 worksheet 和 workbook
          const ws = XLSX.utils.aoa_to_sheet([header, ...data]);
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, '进货统计');

          // 3. 导出
          XLSX.writeFile(wb, '进货统计.xlsx');
        }

        //挂载
        onMounted(()=>{
          All();
          GetSuppliers();
          GetDepartments();
          GetUsers();
        })

      return {
        tableData,
        currentPage,
        pageSize,
        total,
        activeTime,
        timeRange,
        searchform,
        searchref,
        Reset,
        totalAmount,
        totalSupplier,
        totalOrder,
        suppliers,
        deps,
        users,
        handlePageChange,
        rowKey,
        handleTabChange,
        Search,
        Refresh,
        Export,
        selectedRows,
        handleSelectionChange
      }
  }
};
</script>

<style scoped>
.form-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}


/* 添加一些间距和对齐样式 */
.el-table .cell {
  display: flex;
  align-items: center;
  justify-content: center;
}
 
/* 或者针对货品明细列特别处理 */
.el-table [label="货品明细"] .cell {
  padding: 0;
}
 
.el-table [label="货品明细"] .cell > div {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 8px 0;
}
.form-row .el-form-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.stats-box {
  display: flex;
  justify-content: space-around;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.stat-item h3 {
  color: #409eff;
  font-size: 24px;
  margin: 0;
}

.stat-item p {
  color: #606266;
  font-size: 14px;
  margin: 5px 0 0;
}

.action-buttons {
  text-align: left;
  margin-bottom: 20px;
}

/* 调整表格样式 */
.el-table {
  margin-top: 20px;
}

/* 货品明细列标题居中 */
.el-table .el-table__header-wrapper .el-table__header .gutter:last-of-type {
  display: none;
}
</style>